#!/bin/bash -e
# shellcheck disable=SC2034

BUILDER_VERSION=1.4.3

BASE_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
. "${BASE_DIR}/environment.sh"

PATCH_INSTALL_NAME=kylin-patches-installer
FILE_INSTALLER_RUN=${PATCH_INSTALL_NAME}.run

PATCH_BASE_NAME=kylin-patches
FILE_PACKAGE=${PATCH_BASE_NAME}.tar.gz
FILE_PATCHES_LIST=${PATCH_BASE_NAME}.list
FILE_PATCHES_VERSION=${PATCH_BASE_NAME}-version.txt
FILE_PATCHES_CHANGELOG=${PATCH_BASE_NAME}-changelog.html

declare -a DIRS_PATCHES

# Configure variables
ALL_OSVER=false
ALL_MAINLINE=false
ALL_CPU=false
ALL_CPU_HUAWEI=false

# Usage
USAGE=
USAGE="${USAGE:+${USAGE}\n}Usage: $0 [-avh] <Patch Dirs> [<Patch Dirs>...]"
USAGE="${USAGE:+${USAGE}\n}  -a,--cli,--auto     : Auto mode, no user interaction"
USAGE="${USAGE:+${USAGE}\n}  -all-osver          : Not detect OS Version and OS Mainline (v10 or v10sp1 ...)"
USAGE="${USAGE:+${USAGE}\n}  -all-mainline       : Not detect OS Mainline (2107, 2203, 2303, ...)"
USAGE="${USAGE:+${USAGE}\n}  -all-cpu            : Not detect CPU is or not Huawei CPU"
USAGE="${USAGE:+${USAGE}\n}  -all-huawei         : Not detect Huawei CPU model (990, 9006c, m900, ...)"
USAGE="${USAGE:+${USAGE}\n}  -custom [installer] : Custom Installer Script, default is named 'installer.custom.sh.in'"
USAGE="${USAGE:+${USAGE}\n}  -v,--version        : Show version and exit"
USAGE="${USAGE:+${USAGE}\n}  -h,--help           : Show this help message and exit"
USAGE="${USAGE:+${USAGE}\n}  <Patch Dirs>        : Directories containing patches"
USAGE="${USAGE:+${USAGE}\n}"

# Parse Arguments
if [ $# -eq 0 ]; then
    echo -e "${USAGE}"
    exit 1
fi

while [ $# -gt 0 ]; do
    case "$1" in
        -v|--version)
            echo "${BUILDER_VERSION}" && exit 0
            ;;
        -h|--help)
            echo -e "${USAGE}" && exit 0
            ;;
        -a|--cli|--auto)
            INSTALLER_MODE=CLI
            shift
            ;;
        -all-osver)
            ALL_OSVER=true
            ALL_MAINLINE=true
            shift
            ;;
        -all-mainline)
            ALL_MAINLINE=true
            shift
            ;;
        -all-cpu)
            ALL_CPU=true
            shift
            ;;
        -all-huawei)
            ALL_CPU_HUAWEI=true
            shift
            ;;
        -custom)
            INSTALLER_CUSTOMED=true
            shift
            if [ -f "$1" ]; then
                SCRIPT_IN_INSTALLER="$1"
                shift
            else
                SCRIPT_IN_INSTALLER=${SCRIPT_IN_INSTALLER_CUSTOMED}
            fi
            ;;
        *)
            DIRS_PATCHES+=("$1")
            # read -ra DIRS_PATCHES <<< "${DIRS_PATCHES[*]} $1"
            shift
            ;;
    esac
done

# echo -e "Generating Patches Installer ..."
echo -e "正在生成补丁安装器 ..."

# Update List File
rm -f "${FILE_PATCHES_LIST}"
{
    echo "# Sha256Sum | File"
    for DIR_PATCHES in "${DIRS_PATCHES[@]}"; do
        DIR_PATCHES_PARENT=.
        if [ "${DIR_PATCHES:0:1}" = "/" ]; then
            DIR_PATCHES_PARENT=/
        fi
        pushd "${DIR_PATCHES_PARENT}" > /dev/null || exit $?
        find "${DIR_PATCHES#/}" -type f -regextype posix-extended -regex ".*\.(deb|rpm)" -name "*_all.*" -print0 | sort -z | xargs -0 sha256sum
        find "${DIR_PATCHES#/}" -type f -regextype posix-extended -regex ".*\.(deb|rpm)" ! -name "*_all.*" -print0 | sort -z | xargs -0 sha256sum
        popd > /dev/null || exit $?
    done
} >> "${FILE_PATCHES_LIST}"

# Check List File
FILE_PATCHES_LIST_LINES=$(grep -cv "^#" "${FILE_PATCHES_LIST}")
if [ "${FILE_PATCHES_LIST_LINES}" -lt 1 ]; then
    # echo -e "Invalid List File [${FILE_PATCHES_LIST}]. No Patch Package is included."
    # echo -e "Please Check your Arguments!"
    echo -e "无效的列表文件 [${FILE_PATCHES_LIST}]。未包含任何补丁包。"
    echo -e "请检查你的参数！"
    exit 1
fi

# Update Installer
#   Function
sed -e "s|__BASE_NAME__|${PATCH_BASE_NAME}|g" "${SCRIPT_IN_FUNCTION}" > "${SCRIPT_FUNCTION}"
sed -i -e "s|__ALL_OSVER__|${ALL_OSVER}|g" "${SCRIPT_FUNCTION}"
sed -i -e "s|__ALL_MAINLINE__|${ALL_MAINLINE}|g" "${SCRIPT_FUNCTION}"
sed -i -e "s|__ALL_CPU__|${ALL_CPU}|g" "${SCRIPT_FUNCTION}"
sed -i -e "s|__ALL_CPU_HUAWEI__|${ALL_CPU_HUAWEI}|g" "${SCRIPT_FUNCTION}"
#   Installer
sed -e "s|__BASE_NAME__|${PATCH_BASE_NAME}|g" "${SCRIPT_IN_INSTALLER}" > "${SCRIPT_INSTALLER}"
sed -i -e "s|__INSTALLER_MODE__|${INSTALLER_MODE}|g" "${SCRIPT_INSTALLER}"
#   Permissions
chmod 755 "${SCRIPT_INSTALLER}"

# Package All Needed Files
tar --gzip -c -f "${FILE_PACKAGE}" \
    "${SCRIPT_FUNCTION}" \
    "${SCRIPT_INSTALLER}" \
    "${FILE_PATCHES_LIST}" \
    "${FILE_PATCHES_VERSION}" \
    "${FILE_PATCHES_CHANGELOG}" \
    "${DIRS_PATCHES[@]}"

# Update Self Installer in temp folder
SUM=$(sha256sum "${FILE_PACKAGE}" | awk '{print $1}')
sed -e "s|__SHA256SUM__|${SUM}|g" \
    -e "s|__BASE_NAME__|${PATCH_BASE_NAME}|g" \
    -e "s|__INSTALLER__|${SCRIPT_INSTALLER}|g" \
    -e "s|__INSTALLER_MODE__|${INSTALLER_MODE}|g" \
    "${SCRIPT_IN_SELF_INSTALLER}" > "${SCRIPT_SELF_INSTALLER}"

# Add date & time to installer name
if [ "${INSTALLER_MODE}" = "CLI" ]; then
    FILE_INSTALLER_RUN=${PATCH_INSTALL_NAME}-auto-$(date "+%Y%m%d").run
else
    FILE_INSTALLER_RUN=${PATCH_INSTALL_NAME}-$(date "+%Y%m%d").run
fi

# Create Installer Package
cat "${SCRIPT_SELF_INSTALLER}" "${FILE_PACKAGE}" > "${FILE_INSTALLER_RUN}"
chmod +x "${FILE_INSTALLER_RUN}"

# Cleanup temp files
rm -f "${SCRIPT_SELF_INSTALLER}"
rm -f "${SCRIPT_FUNCTION}"
rm -f "${SCRIPT_INSTALLER}"
rm -f "${FILE_PATCHES_LIST}"
rm -f "${FILE_PACKAGE}"

# echo -e "Installer Generated: \e[1;32m${FILE_INSTALLER_RUN}\e[0m"
echo -e "安装器已生成: \e[1;32m${FILE_INSTALLER_RUN}\e[0m"
